from flask import request
from flask import Blueprint, render_template, redirect, url_for, flash
from python.model.user import User
from wtforms import StringField, PasswordField, SubmitField
from wtforms.validators import DataRequired, Email, EqualTo
from python.extensions import db, login_manager
import pymysql
from flask import jsonify

manger_bp = Blueprint('manger', __name__, url_prefix='/manger')

# 在所有使用 pymysql 的地方统一字符集
def get_conn():
    return pymysql.connect(
        host="localhost",
        user="root",
        password='root',
        database="stat",
        charset='utf8mb4',  # 统一使用 utf8mb4
        cursorclass=pymysql.cursors.DictCursor
    )

# @manger_bp.route('/user_manager')
# def user_manager():
#     return render_template('manger/user_manager.html')

# user_controller.py
from flask_login import current_user  # 新增导入

@manger_bp.route('/user_manager')
def user_manager():
    if not current_user.is_admin:
        flash('权限不足，无法访问用户管理')
        return redirect(url_for('main.index'))
    print(f"当前用户: {current_user.username}, 是否管理员: {current_user.is_admin}")
    return render_template('manger/user_manager.html')
@manger_bp.route('/selectallUserInfo', methods=['POST', 'GET'])
def selectallUserInfo():
    page = request.form.get("page")
    limit = request.form.get("limit")
    conn = get_conn()
    cursor = conn.cursor()
    sql1 = "SELECT * FROM user"
    cursor.execute(sql1)
    results1 = cursor.fetchall()
    print(len(results1))

    sql2 = "SELECT * FROM user LIMIT %s, %s"
    limit = int(limit)
    page = int(page)
    start = (page - 1) * limit
    cursor.execute(sql2, (start, limit))
    results2 = cursor.fetchall()
    print(len(results2))
    res = {}

    # 转换数据格式：字典列表 → 字典列表（确保字段名正确）
    formatted_data = [
        {
            "id": item['id'],  # 使用字段名访问
            "username": item['username'],
            "email": item['email'],
            "password_hash": item['password_hash']
        }
        for item in results2
    ]
    res['data'] = formatted_data
    res['code'] = 0
    res['msg'] = ''
    res['count'] = len(results1)
    print(res)
    print(len(results2))
    return jsonify(res)

@manger_bp.route('/deleteUser', methods=['POST'])
def deleteUser():
    try:
        # 1. 验证用户权限
        if not current_user.is_authenticated or not current_user.is_admin:
            return jsonify(success=False, message="权限不足"), 403

        # 2. 获取并验证用户ID
        user_id = request.form.get('id')
        if not user_id:
            return jsonify(success=False, message="缺少用户ID"), 400

        try:
            user_id = int(user_id)  # 确保ID是整数
        except ValueError:
            return jsonify(success=False, message="无效的用户ID"), 400

        # 3. 检查是否尝试删除自己
        if current_user.id == user_id:
            return jsonify(success=False, message="不能删除自己的账户"), 400

        # 4. 查询并验证用户存在
        user = User.query.get(user_id)
        if not user:
            return jsonify(success=False, message="用户不存在"), 404

        # 5. 执行删除
        db.session.delete(user)
        db.session.commit()

        # 6. 返回成功响应
        return jsonify(
            success=True,
            message="删除成功",
            data={
                "deleted_user_id": user_id,
                "remaining_users": User.query.count()  # 可选：返回剩余用户数
            }
        )

    except Exception as e:
        db.session.rollback()
        return jsonify(
            success=False,
            message="服务器错误",
            error=str(e)  # 生产环境应该隐藏具体错误信息
        ), 500